 
/* EXAMPLE
  $('body').popup({
	    title:"Alert! Alert!",
	    message:"This is a test of the emergency alert system!! Don't PANIC!",
	    cancelText:"Cancel me", 
	    cancelCallback: function(){console.log("cancelled");},
	    doneText:"I'm done!",
	    doneCallback: function(){console.log("Done for!");},
	    cancelOnly:false,
      doneClass:'button',
      cancelClass:'button',
      onShow:function(){console.log('showing popup');}
      autoCloseDone:true, //default is true will close the popup when done is clicked.
      suppressTitle:false //Do not show the title if set to true
  });
  
  You can programatically trigger a close by dispatching a "close" event to it.
  
  $('body').popup({title:'Alert',id:'myTestPopup'});
  $("#myTestPopup").trigger("close");
  
 */
(function($) {
    
    $.fn.alert = function(opts) {
    		opts.mawType = "alert";
        return new popup(this[0], opts);
    };
    
  
    $.fn.dialog = function(opts) {
    		opts.mawType = "dialog";
        return new popup(this[0], opts);
    };
    var queue = [];
    var defaultTitle = "消息提示";
    var popup = (function() {
        var popup = function(containerEl, opts) {
            this.mawType = opts.mawType;
            
            if (typeof containerEl === "string" || containerEl instanceof String) {
                this.container = document.getElementById(containerEl);
            } else {
                this.container = containerEl;
            }
            if (!this.container) {
                alert("Error finding container for popup " + containerEl);
                return;
            }
          
            
            try {
                if (typeof (opts) === "string" || typeof (opts) === "number")
                    opts = {message: opts,cancelOnly: "true",cancelText: "OK"};
                this.id = id = opts.id = opts.id || $.uuid(); //opts is passed by reference
                var self = this;
                this.title = opts.suppressTitle?"":(opts.title || defaultTitle);
                this.message = opts.message || "";
               
               	this.width = opts.width || null;
                this.cancelText = opts.cancelText || "取消";
                this.cancelCallback = opts.cancelCallback || function() {
                };
                this.cancelClass = opts.cancelClass || "button_pop";
                
                this.doneText = opts.doneText || "确定";
                this.doneCallback = opts.doneCallback || function(self) {
                	self.hide();
                };
                this.doneClass = opts.doneClass || "button_pop";
                
                
                this.doneText2 = opts.doneText2;
                this.doneCallback2 = opts.doneCallback2 || function(self) {
                	self.hide();
                };
                this.doneClass2 = opts.doneClass2 || "button";
                
                
                this.cancelOnly = opts.cancelOnly || false;
                this.onShow = opts.onShow || function(){};
                this.autoCloseDone=opts.autoCloseDone!==undefined?opts.autoCloseDone:true;
                
                queue.push(this);
                if (queue.length == 1)
                    this.show();
            } catch (e) {
                console.log("error adding popup " + e);
            }
        
        };
        
        popup.prototype = {
            id: null,
            title: null,
            message: null,
            cancelText: null,
            cancelCallback: null,
            cancelClass: null,
            doneText: null,
            doneCallback: null,
            doneClass: null,
            doneText2: null,
            doneCallback2: null,
            doneClass2: null,
            cancelOnly: false,
            onShow: null,
            autoCloseDone:true,
            supressTitle:false,
            width: null,
            show: function() {
                var self = this;
                var headerStyle = null;
                if(this.title != "Alert"){
                	headerStyle = "display:inline";	
                }
                 
	        			var markup = '<div id="' + this.id + '" class="jqPopup hidden" ';
	        			if(this.width){
	        				markup +=" style='width:"+this.width+"' ";	
	        			}
	        			 
	        			markup +=" > ";
	        			markup += '<header style="'+headerStyle+'">' + this.title + '</header>\
	        				<div><div style="width:1px;height:1px;-webkit-transform:translate3d(0,0,0);float:right"></div>' + this.message + '</div>\
	        				<footer style="clear:both;">\
	        					<a href="javascript:;" class="'+this.cancelClass+'" id="cancel">' + this.cancelText + '</a>\
	        					<a href="javascript:;" class="'+this.doneClass+'" id="action1">' + this.doneText + '</a>';
	        			
	        			if(this.doneText2){
	        				markup += 	'<a href="javascript:;" class="'+this.doneClass2+'" id="action2">' + this.doneText2 + '</a>';
	        			}		
	        			markup += '</footer></div></div>';
	        				
                $(this.container).append($(markup));
                
                $("#" + this.id).bind("close", function(){
                	self.hide();
                })
                
                if (this.cancelOnly) {
                    $("#" + this.id).find('A#action1').hide();
                    $("#" + this.id).find('A#action2').hide();
                    $("#" + this.id).find('A#cancel').addClass('center');
                }
                //alert($("#" + this.id).find('A').size());
                
                $("#" + this.id).find('A').each(function() {
                    var button = $(this);
                    var _href = $(this).attr("href");
                    button.bind('click', function(e) {
                    		
                    		var bId = button.attr('id'); 
                        if ( bId == 'cancel') {
                            self.cancelCallback.call(self.cancelCallback, self);
                            self.hide();
                        } else if ( bId == 'action1') {
                            self.doneCallback.call(self.doneCallback, self);
                            if(self.autoCloseDone)
                                self.hide();
                        }else if ( bId == 'action2') {
                        		self.doneCallback2.call(self.doneCallback2, self);
                            if(self.autoCloseDone)
                                self.hide();	
                        }else{
                        	//$.ui.loadContent();
                        	//alert(_href);	
                        }
													
                       e.preventDefault();
                       e.stopPropagation();	
                     
                     });
                });
                self.positionPopup();
                $.blockUI(0.5);
                $('#' + self.id).removeClass('hidden');
                $('#' + self.id).bind("orientationchange", function() {
                    self.positionPopup();
                });
                
                this.onShow(this);
                
                jq("#"+this.id).bind("click", function(e) { 
			            var theTarget = e.target;
			            if (theTarget.nodeType == 3)
			                theTarget = theTarget.parentNode;
			            if ($("body").checkAnchorClick(theTarget)) {
			            		self.hide();
			                e.preventDefault();
			                 
			                return false;
			            }
				        }, true);
            },
            
            hide: function() {
                var self = this;
                $('#' + self.id).addClass('hidden');
                $.unblockUI();
                setTimeout(function() {
                    self.remove();
                }, 250);
            },
            
            remove: function() {
                var self = this;
                var $el=$("#"+self.id);
                 
                $el.find('BUTTON#action').unbind('click');
                $el.find('BUTTON#cancel').unbind('click');
                $el.unbind("orientationchange").remove();
                queue.splice(0, 1);
                if (queue.length > 0)
                    queue[0].show();
            },
            
            positionPopup: function() {
                var popup = $('#' + this.id);
                popup.css("top", ((window.innerHeight / 2.5) + window.pageYOffset) - (popup[0].clientHeight / 2) + "px");
                popup.css("left", (window.innerWidth / 2) - (popup[0].clientWidth / 2) + "px");
            }
        };
        
        return popup;
    })();
    var uiBlocked = false;
    $.blockUI = function(opacity) {
        if (uiBlocked)
            return;
        opacity = opacity ? " style='opacity:" + opacity + ";'" : "";
        $('BODY').prepend($("<div id='mask'" + opacity + "></div>"));
        $('BODY DIV#mask').bind("touchstart", function(e) {
            e.preventDefault();
        });
        $('BODY DIV#mask').bind("touchmove", function(e) {
            e.preventDefault();
        });
        uiBlocked = true
    };
    
    $.unblockUI = function() {
        uiBlocked = false;
        $('BODY DIV#mask').unbind("touchstart");
        $('BODY DIV#mask').unbind("touchmove");
        $("BODY DIV#mask").remove();
    };
    
})(jq);